﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LorraineSec.ServerApplication
{
    public partial class PasswordChanger : Form
    {
        private string curPass;
        private string newPass;

        /// <summary>
        /// Constructs a PasswordChanger GUI
        /// </summary>
        /// <param name="p">The current password</param>
        public PasswordChanger(string p)
        {
            InitializeComponent();
            this.KeyPreview = true;

            curPass = p;
            if (curPass == null)
                CurrentEdit.Enabled = false;
        }

        /// <summary>
        /// Generates a PasswordChanger GUI and blocks until the form closes.
        /// </summary>
        /// <param name="currentPassword">The current password.</param>
        /// <returns>The new password or null if the form is cancelled.</returns>
        public static string PromptChangePassword(string currentPassword)
        {
            PasswordChanger form = new PasswordChanger(currentPassword);
            form.ShowDialog();
            return form.newPass;
        }

        private void AcceptButton_Click(object sender, EventArgs e)
        {
            if (curPass == null || CurrentEdit.Text.Equals(curPass))
            {
                if (NewEdit.Text.Equals(RepeatEdit.Text))
                {
                    newPass = NewEdit.Text;
                    Close();
                }
                else
                {
                    MessageBox.Show("New Passwords Do Not Match");
                }
            }
            else
            {
                MessageBox.Show("Current Password Incorrect");
            }
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            newPass = null;
            Close();
        }

        private void PasswordChanger_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    CancelButton_Click(null, null);
                    break;
                case Keys.Enter:
                    AcceptButton_Click(null, null);
                    break;
            }
        }
    }
}
